﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Modules;
using anaii.EasyNews.Data;
using DotNetNuke.UI.Skins;
using DotNetNuke.UI.Skins.Controls;
using System.Web.Query.Dynamic;
using System.ComponentModel;
using DotNetNuke.Services.Localization;

namespace anaii.EasyNews
{
    public partial class Edit : PortalModuleBase
    {
        protected DropDownList ddlLanguages;
        private bool IsEditingNews
        {
            get
            {
                bool retval = true;
                if (ViewState["IsEditingNews"] != null && bool.TryParse(ViewState["IsEditingNews"].ToString(), out retval))
                    return retval;
                return true;
            }
            set
            {
                ViewState["IsEditingNews"] = value;
            }
        }

        #region Base

        protected override void OnInit(EventArgs e)
        {
            if (DotNetNuke.Framework.AJAX.IsInstalled())
                DotNetNuke.Framework.AJAX.RegisterScriptManager();

            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                gvCategories.Visible = false;
                gvNews.Visible = true;
                IsEditingNews = true;
                BaseBind();
                DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(btnAddNew, "All unsaved content will be lost, add new ? ");
                DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(btnManage, "All unsaved content will be lost, switch to managing ? ");
                DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(btnCancel, "All unsaved content will be lost, cancel ? ");
            }
        }

        #endregion

        #region Private methods

        private void BaseBind()
        {
            ddlLanguages.Items.Clear();
            foreach (KeyValuePair<string, Locale> val in Localization.GetLocales(this.PortalId))
            {
                ddlLanguages.Items.Add(new ListItem(val.Value.Text, val.Value.Code));
            }
        }

        #endregion

        #region Events

        protected void gvCategories_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                EasyNewsType item = e.Row.DataItem as EasyNewsType;
                if (item != null)
                {
                    LinkButton lnkEdit = e.Row.FindControl("lnkEdit") as LinkButton;
                    if (lnkEdit != null)
                    {
                        lnkEdit.Click += new EventHandler(lnkEditCategory_Click);
                        lnkEdit.CommandArgument = item.TypeID.ToString();
                        DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(lnkEdit, "All unsaved content will be lost, continue to edit news category " + item.TypeID.ToString() + " ?");
                    }
                    LinkButton lnkDelete = e.Row.FindControl("lnkDelete") as LinkButton;
                    if (lnkDelete != null)
                    {
                        lnkDelete.Click += new EventHandler(lnkDeleteCategory_Click);
                        lnkDelete.CommandArgument = item.TypeID.ToString();
                        DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(lnkDelete, "Are you sure you want to delete this news category ?");
                    }
                }
            }
        }

        protected void gvNews_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                EasyNews.Data.EasyNewsDBDataContext db = new anaii.EasyNews.Data.EasyNewsDBDataContext();
                EasyNew item = db.EasyNews.First(p => p.NewsID == int.Parse(gvNews.DataKeys[e.Row.RowIndex][0].ToString()));
                if (item != null)
                {
                    LinkButton lnkEdit = e.Row.FindControl("lnkEdit") as LinkButton;
                    if (lnkEdit != null)
                    {
                        lnkEdit.Click += new EventHandler(lnkEdit_Click);
                        lnkEdit.CommandArgument = item.NewsID.ToString();
                        DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(lnkEdit, "All unsaved content will be lost, continue to edit news " + item.NewsID.ToString() + " ?");
                    }
                    LinkButton lnkDelete = e.Row.FindControl("lnkDelete") as LinkButton;
                    if (lnkDelete != null)
                    {
                        lnkDelete.Click += new EventHandler(lnkDelete_Click);
                        lnkDelete.CommandArgument = item.NewsID.ToString();
                        DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(lnkDelete, "Are you sure you want to delete this news ?");
                    }
                    Label lblType = e.Row.FindControl("lblType") as Label;
                    if (lblType != null)
                    {
                        lblType.Text = db.EasyNewsTypes.First(p => p.TypeID == item.TypeID).Name;
                    }
                    Label lblTitle = e.Row.FindControl("lblTitle") as Label;
                    if (lblTitle != null)
                    {
                        lblTitle.Text = item.dnn_EasyNewsTranslations.First(p => p.NewsID == item.NewsID).Title;
                    }
                    Label lblSmallDescription = e.Row.FindControl("lblSmallDescription") as Label;
                    if (lblSmallDescription != null)
                    {
                        lblSmallDescription.Text = item.dnn_EasyNewsTranslations.First(p => p.NewsID == item.NewsID).ShortDescription;
                    }
                }
            }
        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            LinkButton lnkDelete = (LinkButton)sender;
            if (lnkDelete != null)
            {
                EasyNews.Data.EasyNewsDBDataContext db = new anaii.EasyNews.Data.EasyNewsDBDataContext();
                EasyNew currentNews = new EasyNew();
                int newsID = -1;
                if (int.TryParse(lnkDelete.CommandArgument, out newsID))
                    currentNews = db.EasyNews.First(p => p.NewsID == newsID);
                db.EasyNews.DeleteOnSubmit(currentNews);
                db.SubmitChanges();
                newsLinqDS.DataBind();
                gvNews.DataBind();
            }
        }

        protected void lnkEdit_Click(object sender, EventArgs e)
        {
            LinkButton lnkEdit = (LinkButton)sender;
            if (lnkEdit != null)
            {
                EasyNews.Data.EasyNewsDBDataContext db = new anaii.EasyNews.Data.EasyNewsDBDataContext();
                ((GridView)((lnkEdit.Parent.Parent as GridViewRow).Parent.Parent)).SelectedIndex = (lnkEdit.Parent.Parent as GridViewRow).RowIndex;
                EasyNew currentNews = new EasyNew();
                int newsID = -1;
                if (int.TryParse(lnkEdit.CommandArgument, out newsID))
                    currentNews = db.EasyNews.First(p => p.NewsID == newsID);
                fcEditNewsControl.BindData(currentNews);
                panActionsEdit.Visible = true;
            }
        }

        protected void lnkDeleteCategory_Click(object sender, EventArgs e)
        {
            LinkButton lnkDelete = (LinkButton)sender;
            if (lnkDelete != null)
            {
                EasyNews.Data.EasyNewsDBDataContext db = new anaii.EasyNews.Data.EasyNewsDBDataContext();
                EasyNewsType currentNews = new EasyNewsType();
                int typeID = -1;
                if (int.TryParse(lnkDelete.CommandArgument, out typeID))
                    currentNews = db.EasyNewsTypes.First(p => p.TypeID == typeID);
                db.EasyNewsTypes.DeleteOnSubmit(currentNews);
                db.SubmitChanges();
                categoriesDataSource.DataBind();
                gvCategories.DataBind();
            }
        }

        protected void lnkEditCategory_Click(object sender, EventArgs e)
        {
            LinkButton lnkEdit = (LinkButton)sender;
            if (lnkEdit != null)
            {
                EasyNews.Data.EasyNewsDBDataContext db = new anaii.EasyNews.Data.EasyNewsDBDataContext();
                ((GridView)((lnkEdit.Parent.Parent as GridViewRow).Parent.Parent)).SelectedIndex = (lnkEdit.Parent.Parent as GridViewRow).RowIndex;
                EasyNewsType currentNews = new EasyNewsType();
                int typeID = -1;
                if (int.TryParse(lnkEdit.CommandArgument, out typeID))
                    currentNews = db.EasyNewsTypes.First(p => p.TypeID == typeID);
                fcEditCategoriesControl.BindData(currentNews);
                panActionsEdit.Visible = true;
            }
        }

        protected void btnManage_Click(object sender, EventArgs e)
        {
            fcEditNewsControl.Clear(true);
            fcEditCategoriesControl.Clear(true);
            panActionsEdit.Visible = false;
            if (!IsEditingNews)
            {
                gvNews.Visible = true;
                gvCategories.Visible = false;
                IsEditingNews = true;
                btnManage.Text = "Manage categories";
            }
            else
            {
                gvNews.Visible = false;
                gvCategories.Visible = true;
                IsEditingNews = false;
                btnManage.Text = "Manage news";
            }

            categoriesDataSource.DataBind();
            gvCategories.DataBind();
            newsLinqDS.DataBind();
            gvNews.DataBind();
        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            if (IsEditingNews)
            {
                EasyNew currentFund = new EasyNew();
                fcEditNewsControl.BindData(currentFund);
                gvNews.SelectedIndex = -1;
                panActionsEdit.Visible = true;
            }
            else
            {
                EasyNewsType currentFundCategory = new EasyNewsType();
                fcEditCategoriesControl.BindData(currentFundCategory);
                gvCategories.SelectedIndex = -1;
                panActionsEdit.Visible = true;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (IsEditingNews)
            {
                bool retVal = fcEditNewsControl.Save(UserId);
                if (retVal)
                {
                    Skin.AddModuleMessage(this, "Save news status!", "Save successful", ModuleMessage.ModuleMessageType.GreenSuccess);
                    fcEditNewsControl.Clear(true);
                    panActionsEdit.Visible = false;
                    newsLinqDS.DataBind();
                    gvNews.DataBind();
                }
                else
                {
                    Skin.AddModuleMessage(this, "Save news status!", "Save has not been successful, error occurred during save!", ModuleMessage.ModuleMessageType.RedError);
                }
            }
            else
            {
                bool retVal = fcEditCategoriesControl.Save(UserId);
                if (retVal)
                {
                    Skin.AddModuleMessage(this, "Save news category status!", "Save successful", ModuleMessage.ModuleMessageType.GreenSuccess);
                    fcEditCategoriesControl.Clear(true);
                    panActionsEdit.Visible = false;
                    categoriesDataSource.DataBind();
                    gvCategories.DataBind();
                }
                else
                {
                    Skin.AddModuleMessage(this, "Save news category status!", "Save has not been successful, error occurred during save!", ModuleMessage.ModuleMessageType.RedError);
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            fcEditNewsControl.Clear(true);
            fcEditCategoriesControl.Clear(true);
            panActionsEdit.Visible = false;
        }

        protected void ddlLanguages_SelectedIndexChanged(object sender, EventArgs e)
        {
            Skin.AddModuleMessage(this, "Content editing language changed!", "Current culture for editing: " + ddlLanguages.SelectedValue, ModuleMessage.ModuleMessageType.BlueInfo);
            fcEditNewsControl.RebindCulture(ddlLanguages.SelectedValue);
            fcEditCategoriesControl.RebindCulture(ddlLanguages.SelectedValue);
        }

        #endregion

        
    }
}